package net.weitalk.concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import static net.weitalk.concurrent.BlockingQueueConsumerProducer.EXIT_MESSAGE;

/**
 * 如果使用非 Blocking 的队列，
 * 那么我们就要自己去实现轮询、条件判断（如检查 poll 返回值是否 null）等逻辑，
 * 如果没有特别的场景要求，Blocking 实现起来代码更加简单、直观。
 */

class Producer implements Runnable {
    private BlockingQueue<String> queue;

    public Producer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(5);
                String msg = "Message" + i;
                System.out.println("Produce new item: " + msg);
                queue.put(msg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            System.out.println("Time to say good bye!");
            queue.put(EXIT_MESSAGE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer implements Runnable {
    private BlockingQueue<String> queue;

    public Consumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            String msg;
            while (!EXIT_MESSAGE.equalsIgnoreCase((msg = queue.take()))) {
                System.out.println("Consumed item: " + msg);
                Thread.sleep(10);
            }
            System.out.println("Got exit message, bye!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class BlockingQueueConsumerProducer {
    public static final String EXIT_MESSAGE = "Good bye!";

    public static void main(String[] args) {
        //使用较小的队列，以更好地在输出中展示其影响
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}
